<?php

namespace app\api\service\exchange;

use app\model\exchange\ExchangeRateModel;
use hunma\exception\ApiException;

class ExchangeService
{

    public function get(array $getAllParams)
    {
        if ($getAllParams['amount'] <= 0) {
            throw new ApiException("金额必须大于0", 400);
        }

        // 查询汇率表
        $from = ExchangeRateModel::getOne(['currency_name' => strtoupper($getAllParams['to'])]);
        $to = ExchangeRateModel::getOne(['currency_name' => strtoupper($getAllParams['from'])]);
        if (!$from || !$to) {
            // 查询汇率表
            $from = ExchangeRateModel::getOne(['currency_code' => strtoupper($getAllParams['to'])]);
            $to = ExchangeRateModel::getOne(['currency_code' => strtoupper($getAllParams['from'])]);
            if (!$from || !$to) {
                throw new ApiException("币种不存在", 400);
            }
        }

        // 汇率均为 rate_to_cny，先转CNY，再转目标币
        // 金额(目标币) = 金额(源币) * 源币兑CNY / 目标币兑CNY
        $result = $getAllParams['amount'] * $from['rate_to_cny'] / $to['rate_to_cny'];

        return [
            'from' => $getAllParams['from'],
            'to' => $getAllParams['to'],
            'amount' => round($getAllParams['amount'], 4),
            'converted_amount' => round($result, 4),
            'from_symbol' => $from['symbol'],
            'to_symbol' => $to['symbol'],
            'from_name' => $from['currency_name'],
            'to_name' => $to['currency_name'],
            'rate' => round($from['rate_to_cny'] / $to['rate_to_cny'], 6),
        ];
    }
}